package com.onlyphoto.onlymall.base;

import com.google.gson.Gson;
import com.onlyphoto.onlymall.api.Api;
import com.onlyphoto.onlymall.api.ApiService;

import io.reactivex.ObservableTransformer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function;

/**
 * Created by gaochujia on 2019-6-26.
 */
public abstract class BaseModel {


    public CompositeDisposable mDisposable = new CompositeDisposable();

    /**
     * 初始化调用网络请求
     *
     * @return
     */
    public ApiService apiService() {
        return Api.createApi().create(ApiService.class);
    }


    /**
     * 取消网络请求
     */
    public void onDestroy() {
        if (mDisposable != null) {
            mDisposable.dispose();
            mDisposable.clear();
        }
    }

    /**
     * Rx优雅处理服务器返回
     *
     * @param <T>
     * @return
     */
    public <T> ObservableTransformer<BaseNetworkResponse<T>, T> handleResult() {
        return upstream -> upstream.map((Function<BaseNetworkResponse<T>, T>) BaseNetworkResponse::getData);
    }

    public String getJsonString(Object o) {
        Gson gson = new Gson();
        return gson.toJson(o);
    }
}
